package com.cndragon.baby.notification
{
	public class NotificationFactory
	{
		private static var _instance:NotificationFactory;
		
		private var _commandMgr:CommandMgr;
		private var _logicMgr:LogicMgr;
		
		public function NotificationFactory(s:S)
		{
			_commandMgr = CommandMgr.getInstance();
			_logicMgr = LogicMgr.getInstance();
		}
		
		static public function getInstance():NotificationFactory
		{
			if(_instance==null)
			{
				_instance = new NotificationFactory(new S());
			}
			return _instance;
		}
		
		
		public function registerLogic( logic:SimpleLogic ):void
		{
			_logicMgr.registerLogic( logic );
		}
		
		
		/**
		 * 注册 Command。一个 notificationID 只能对应一个 Command；一个 Command 可以被多个 notificationID 注册。
		 * 注册后，只要通过 sendNotification() 方法广播消息，
		 * 注册此消息的 CommandClass 就会被执行 execute() 方法。
		 * @param notificationID
		 * @param CommandClass
		 * 
		 */		
		public function registerCommand(notificationID:int, CommandClass:Class):void
		{
			_commandMgr.registerCommand(notificationID, CommandClass);
		}
		
		
		/**
		 * 解除注册后，所有Command类都不会响应这个notificationID
		 * @param notificationID
		 * 
		 */		
		public function unRegisterCommand(notificationID:int):void
		{
			_commandMgr.unRegisterCommand(notificationID);
		}
		
		
		/**
		 * 删除 Command
		 * @param commandClass
		 * 
		 */		
		public function removeCommand(commandClass:Class):void
		{
			_commandMgr.removeCommand(commandClass);
		}
		
		
		/**
		 * 广播消息
		 * 注册过这个消息的 Command 会被执行
		 * 注册过这个消息的 Logic 会被执行
		 * @param notificationID
		 * @param body
		 * 
		 */		
		public function sendNotification(notificationID:int, body:Object=null):void
		{
			trace("[NotificationFactory.sendNotification]");
			//找到这个notificationID注册过的唯一的Command类
			var command:SimpleCommand = _commandMgr.getCommand(notificationID);
			var notification:SimpleNotification = new SimpleNotification(notificationID,body);
			if(command)
				command.execute(notification);
			
			//找到注册过这个notificationID的多个Logic实例
			var logicList:Array = _logicMgr.getLogicListByNotificationID( notificationID );
			for each (var logic:SimpleLogic in logicList) 
			{
				logic.handleNotification( notification );
			}
			
			logicList = null;
			command = null;
			notification = null;
		}
	}
}

class S{}